package mark.tom.friend.view.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.liaoinstan.springview.widget.SpringView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import mark.tom.friend.app.CustomApplication;
import mark.tom.friend.base.FriendFooter;
import mark.tom.friend.base.FriendHeader;
import mark.tom.friend.base.activity.BaseActivity;
import mark.tom.friend.base.util.RxViewUtil;
import mark.tom.friend.bean.bo.AppInfoBO;
import mark.tom.friend.bean.vo.AppInfoVO;
import mark.tom.friend.component.DaggerAppListComponent;
import mark.tom.friend.consts.ActivityRouterConsts;
import mark.tom.friend.consts.BundleKeyConsts;
import mark.tom.friend.contract.AppListContract;
import mark.tom.friend.module.AppListModule;
import mark.tom.friend.presenter.AppListPresenter;
import mark.tom.friend.roll.R;
import mark.tom.friend.view.adapter.AppListAdapter;
import timber.log.Timber;

@Route(path = ActivityRouterConsts.ROUTER_APP_LIST)
public class AppListActivity extends BaseActivity implements AppListContract.View {

    @Autowired AppBarLayout appBarLayout;
    @Autowired Toolbar appToolBar;
    @Autowired RecyclerView appListView;
    @Autowired FloatingActionButton appSearchButton;
    @Autowired SpringView appListSpringView;

    @Autowired(innerWired = true) @Inject AppListPresenter mPresenter;

    // 对话框
    private AlertDialog mDialog;
    // 列表适配器
    private AppListAdapter mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.layout_app_list;
    }

    @Override
    protected void onCreate(View contentView, Bundle savedInstanceState) {
        DaggerAppListComponent.builder()
                .appComponent(CustomApplication.get(this).getAppComponent())
                .appListModule(new AppListModule(this))
                .build()
                .inject(this);
        // 使用路由框架初始化
        ARouter.getInstance().inject(this, mPresenter, contentView, savedInstanceState);
        // 初始化ToolBar显示信息
        initToolBar();
        // 设置RecyclerView
        initRecyclerView();
        // 绑定视图事件
        bindViewListener();
        // 初始化数据
        mPresenter.onStart();
    }

    private void initToolBar() {
        // 设置ToolBar
        setToolBar(appToolBar);
        appToolBar.setTitle(R.string.activity_app_list_title);
    }

    private void initRecyclerView() {
        appListView.setLayoutManager(new LinearLayoutManager(this));
        appListView.setHasFixedSize(true);
        mAdapter = new AppListAdapter();
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(true);
        mAdapter.setNotDoAnimationCount(7);
        mAdapter.bindToRecyclerView(appListView);
        mAdapter.setEmptyView(R.layout.layout_empty, appListView);
        // 允许刷新和不允许加载更多
        appListSpringView.setGive(SpringView.Give.TOP);
        appListSpringView.setType(SpringView.Type.FOLLOW);
        appListSpringView.setHeader(new FriendHeader(this, R.mipmap.app_refresh));
        appListSpringView.setFooter(new FriendFooter(this, 0));
    }

    private void bindViewListener() {
        RxViewUtil.bindViewClickListener(appToolBar, bindToLifecycle(), new Consumer<View>() {
            @Override
            public void accept(@NonNull View view) {
                // 回到顶部
                appListView.smoothScrollToPosition(0);
            }
        });
        RxViewUtil.bindViewClickListener(appSearchButton, bindToLifecycle(), new Consumer<View>() {
            @Override
            public void accept(View view) {
                if (null == mDialog) {
                    mDialog = createAlertDialog();
                }
                if (!mDialog.isShowing()) {
                    mDialog.show();
                }
            }
        });
        // 列表视图事件绑定
        appListView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter mAdapter, View view, int position) {
                AppInfoBO appInfo = (AppInfoBO) mAdapter.getItem(position);
                if (null == appInfo) {
                    return;
                }
                Intent data = new Intent();
                data.putExtra(BundleKeyConsts.BUNDLE_KEY_APP_INFO, appInfo);
                setResult(RESULT_OK, data);
                finish();
            }
        });
        // 下拉刷新事件
        appListSpringView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                String key = null;
                if (null != mDialog) {
                    EditText appFilterEditText = mDialog.findViewById(R.id.appFilterEditText);
                    if (null != appFilterEditText) {
                        key = appFilterEditText.getText().toString();
                    }
                }
                if (TextUtils.isEmpty(key)) {
                    key = null;
                }
                // 刷新数据
                refreshListView(key);
            }

            @Override
            public void onLoadmore() {
            }
        });
        // 为了解决手势事件冲突
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                appListSpringView.setEnable(verticalOffset == 0);
            }
        });
    }

    private AlertDialog createAlertDialog() {
        return new AlertDialog.Builder(AppListActivity.this, R.style.Theme_AppCompat_Light_Dialog_Alert)
                .setTitle(R.string.app_list_dialog_title)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        refreshListView();
                    }
                })
                .setView(R.layout.dialog_appfilter)
                .setNegativeButton(android.R.string.no, null)
                .create();
    }

    private void refreshListView(String key) {
        // 重新加载数据
        mPresenter.listAppInfoListByKey(key)
                .filter(new Predicate<AppInfoBO>() {
                    @Override
                    public boolean test(@NonNull AppInfoBO appInfoBO) {
                        return !appInfoBO.getPackageName().equals(getPackageName());
                    }
                })
                .compose(this.<AppInfoBO>bindToLifecycle())
                .subscribe(new Observer<AppInfoBO>() {

                    List<AppInfoVO> appInfoList = new ArrayList<AppInfoVO>();

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        appInfoList.clear();
                    }

                    @Override
                    public void onNext(@NonNull AppInfoBO appInfoBO) {
                        appInfoList.add(appInfoBO);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Timber.e(e);
                    }

                    @Override
                    public void onComplete() {
                        // 刷新界面
                        mAdapter.setNewData(appInfoList);
                        // 停止刷新
                        appListSpringView.onFinishFreshAndLoad();
                    }
                });
    }

    @SuppressLint("CheckResult")
    @Override
    public void refreshListView() {
        Observable.just(1)
                .delay(500, TimeUnit.MILLISECONDS)
                .compose(this.bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(@NonNull Object o) {
                        appListSpringView.callFresh();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
    }

}
